/******************************************************************************
* Copyright (C) 2016, Xiaohua Semiconductor Co.,Ltd All rights reserved.
*
* This software is owned and published by:
* Xiaohua Semiconductor Co.,Ltd ("XHSC").
*
* BY DOWNLOADING, INSTALLING OR USING THIS SOFTWARE, YOU AGREE TO BE BOUND
* BY ALL THE TERMS AND CONDITIONS OF THIS AGREEMENT.
*
* This software contains source code for use with XHSC
* components. This software is licensed by XHSC to be adapted only
* for use in systems utilizing XHSC components. XHSC shall not be
* responsible for misuse or illegal use of this software for devices not
* supported herein. XHSC is providing this software "AS IS" and will
* not be responsible for issues arising from incorrect user implementation
* of the software.
*
* Disclaimer:
* XHSC MAKES NO WARRANTY, EXPRESS OR IMPLIED, ARISING BY LAW OR OTHERWISE,
* REGARDING THE SOFTWARE (INCLUDING ANY ACOOMPANYING WRITTEN MATERIALS),
* ITS PERFORMANCE OR SUITABILITY FOR YOUR INTENDED USE, INCLUDING,
* WITHOUT LIMITATION, THE IMPLIED WARRANTY OF MERCHANTABILITY, THE IMPLIED
* WARRANTY OF FITNESS FOR A PARTICULAR PURPOSE OR USE, AND THE IMPLIED
* WARRANTY OF NONINFRINGEMENT.
* XHSC SHALL HAVE NO LIABILITY (WHETHER IN CONTRACT, WARRANTY, TORT,
* NEGLIGENCE OR OTHERWISE) FOR ANY DAMAGES WHATSOEVER (INCLUDING, WITHOUT
* LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION,
* LOSS OF BUSINESS INFORMATION, OR OTHER PECUNIARY LOSS) ARISING FROM USE OR
* INABILITY TO USE THE SOFTWARE, INCLUDING, WITHOUT LIMITATION, ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES OR LOSS OF DATA,
* SAVINGS OR PROFITS,
* EVEN IF Disclaimer HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
* YOU ASSUME ALL RESPONSIBILITIES FOR SELECTION OF THE SOFTWARE TO ACHIEVE YOUR
* INTENDED RESULTS, AND FOR THE INSTALLATION OF, USE OF, AND RESULTS OBTAINED
* FROM, THE SOFTWARE.
*
* This software may be replicated in part or whole for the licensed use,
* with the restriction that this Disclaimer and Copyright notice must be
* included with each copy of this software, whether used in part or whole,
* at all times.
*/
/******************************************************************************/
/** \file main.c
 **
 ** A detailed description is available at
 ** @link Sample Group Some description @endlink
 **
 **   - 2016-02-16  1.0  XYZ First version for Device Driver Library of Module.
 **
 ******************************************************************************/

/******************************************************************************
 * Include files
 ******************************************************************************/
#include "ddl.h"
#include "bt.h"
#include "lpm.h"
#include "gpio.h"
#include "adc.h"
#include "bgr.h"
#include "uart.h"
#include "CalcSys_L32.h"
#include "wdt.h"
#include <stdio.h>
#include <time.h>
/******************************************************************************
 * Local pre-processor symbols/macros ('#define')
 ******************************************************************************/
#define  LED_PORT     *((volatile uint32_t *)((uint32_t)&M0P_GPIO->P0OUT + 0x80u))
#define  LED_SEL(x)   { LED_PORT &= 0xffffffc7;\
                        LED_PORT |= x<<3;}  

#define  GRP_PORT     *((volatile uint32_t *)((uint32_t)&M0P_GPIO->P0OUT + 0xc0u))
#define  GRP_SEL(x)   { GRP_PORT |=0x78;\
                        GRP_PORT &=~(1<<(x+3));}

#define SET(x)   *((volatile uint32_t *)((uint32_t)&M0P_GPIO->P0OUT + (x>>4) * GPIO_GPSZ))\
                  |= ((1UL)<<(x&0x0f))
#define CLR(x)   *((volatile uint32_t *)((uint32_t)&M0P_GPIO->P0OUT + (x>>4) * GPIO_GPSZ))\
                  &= ~((1UL)<<(x&0x0f)) 
                    
//#define UART_DEBUG
                    
#define BLOCK_OUT       0x32
#define LED_ERR_OUT     0x14
#define BUZZER          0x15
/*******************************************************************************
 * Function implementation - global ('extern') and local ('static')
 ******************************************************************************/
void App_ClkInit(void);
void App_Rch4MHzTo24MHz(void);
void App_GpioInit(void);
void ADC_init(void);
void BT_TIM0_int(void);
void BT_TIM1_int(void);
void BT_TIM2_int(void);
void App_UartInit(void);
void detected_output(void);
void cancel_output(void);
void App_WdtInit(void);
void App_WdtInit1(void);
unsigned char CalcPackageSum(unsigned char* packge,int len);
void uart1_sendStr(uint8_t *data, uint32_t len);
int clk_state,state_bef;
int clk_low_t,clk_high_t,clk_high_cnt;
uint8_t pd_num;
uint8_t adc_flag,adc_vt_flag;
uint16_t adc_data=0;
uint16_t adc_buf[5][32];
uint16_t adc_buf2[34];
int test_cnt;
uint16_t adc_vt_buf[5][32];
uint8_t send_buf[70];
uint8_t PD_mode = 0x02;
uint8_t send_flag;
int buzzle_count=0;
int buzzle_count_s=0;
int buzzle_cnt=0;
uint8_t out_flag=0;
int buzz_flag=0;
int buzzle_state;
uint8_t pwr_flag;
int Tick;
int tick_cnt;
DEV_INFO dev1;
int TEST_FLAG;
uint8_t clk_pwr_t,pwr_down_cnt,pwr_up_cnt;
uint8_t pwr_pst = 0;
uint8_t cal_cnt,cal_flg;
uint8_t delay_flag,output;
int delay_count,out1_cnt,out0_cnt,pwr_cnt,pwr_down,power_count;
int pwr_state = 1;      //默认高功率
uint8_t wdt_flag = 1;
uint8_t start_flag = 1;
unsigned char memorycal[2*1024];
 static int ncd = 0;
/**
 ******************************************************************************
 ** \brief  Main function of project
 **
 ** \return uint32_t return value, if needed
 **
 ** This sample
 **
 ******************************************************************************/


void led_Cmd(uint8_t num)   //0-31
{
    uint8_t led_arr,led_num;
    led_arr = num/8 +3;    //P33 34 35 36
    led_num = num%8;       //p23 24 25
    Gpio_WriteOutputIO(GpioPort3, GpioPin3, (GpioPin3==led_arr)?0:1);
    Gpio_WriteOutputIO(GpioPort3, GpioPin4, (GpioPin4==led_arr)?0:1);
    Gpio_WriteOutputIO(GpioPort3, GpioPin5, (GpioPin5==led_arr)?0:1);
    Gpio_WriteOutputIO(GpioPort3, GpioPin6, (GpioPin6==led_arr)?0:1);
    
    Gpio_WriteOutputIO(GpioPort2, GpioPin3, (led_num & 0x01));
    Gpio_WriteOutputIO(GpioPort2, GpioPin4, (led_num >> 1) & 0x01);
    Gpio_WriteOutputIO(GpioPort2, GpioPin5, (led_num >> 2) & 0x01);
}

unsigned char CalcPackageSum(unsigned char* packge,int len)	//累加+0x10 & 0xFF
{	
    unsigned char ack=0;
    ack = 0x10 + packge[0];
    for (int i = 1; i < len; i++) 
    {
        ack += packge[i];
    }
    ack = (unsigned char)(ack & 0xFF);
    return ack;
}

void detected_output(void)
{
    CLR(0x32);
//#ifndef UART_DEBUG 
//    out_flag = 1;
//#endif
}
void cancel_output(void)
{
    SET(0x32);     
//#ifndef UART_DEBUG
//    buzzle_count=0;
//    buzzle_count_s = 0;
//    buzzle_cnt = 0;
//    out_flag = 0;       //遮挡标志位
//    buzz_flag = 0;    //蜂鸣器标志位
//    SET(BUZZER);          //蜂鸣器
//#endif
}


  int32_t main(void)
{
    uint16_t error=0;
    uint8_t *pcal;
    App_ClkInit();
    App_Rch4MHzTo24MHz();
    App_GpioInit();
    CLR(0x15);
    BT_TIM0_int();
    ADC_init();

    dev1.nCalcMemSize=2*1024;
    dev1.pCalcMemBuf=(unsigned char *)memorycal;
    int ret = InitCalcSys_L32(&dev1);
    delay100us(10000);
#ifdef UART_DEBUG
    App_WdtInit1();
    App_UartInit();
#else
    App_WdtInit();
//    SET(0x01);
//    SET(0x02);
#endif
    SET(0x15);    //蜂鸣器
    SET(0x14);  //坏灯指示灯
    SET(0x32);
    Wdt_Start();
//    for(uint8_t i=0;i<34;i++)
//    {
//      adc_buf2[i] = 1700;
//    }
    while (1)
    {
        Wdt_Feed();
        if(send_flag)
        {       
            
            send_flag = 0;
            memset(send_buf,0,sizeof(send_buf));
            send_buf[0] = 0x28;
            send_buf[1] = 0x76;
            //send_buf[2] = PD_mode;
            if(PD_mode == 0)
            {
                memcpy(&send_buf[3],&adc_buf[4],60);
                send_buf[2] = 4;
            }
            else if(PD_mode == 1)
            {
                memcpy(&send_buf[3],&adc_buf[0],64);
                send_buf[2] = 0;
            }
            else if(PD_mode == 2)
            {
                memcpy(&send_buf[5],&adc_buf[1],64);
                send_buf[2] = 1;
            }            
            else if(PD_mode == 3)
            {
                memcpy(&send_buf[3],&adc_buf[2],62);
                send_buf[2] = 2;
            }
            
            else if(PD_mode == 4)
            {
                memcpy(&send_buf[7],&adc_buf[3],64);
                send_buf[2] = 3;
            }
            send_buf[67] = CalcPackageSum(send_buf,67);
#ifdef UART_DEBUG
            uart1_sendStr(send_buf,68);
#endif
            dev1.pScanBuf->ucScanFlag= send_buf[2];
            dev1.pScanBuf->usDataSize=64;
            
            pcal=dev1.pScanBuf->pBuf;
            for(uint8_t i=0;i<64;i++)
            {
              *(pcal+i)=send_buf[3+i];
            }
            SwapFrame_L32(&dev1);
            
            if(delay_flag == 1)
            {
                pwr_cnt++;
                if(pwr_cnt >= 8)
                {
                    pwr_cnt = 0;
                    delay_flag = 0;
                }
            }
#if 1
            if(delay_flag == 0)
            {
                if(pwr_state == 0)
                {
                    int ret = 0;
//                    if((send_buf[2] == 0) || (send_buf[2] == 1) || (send_buf[2] == 2))
//                    {
//                        int cnt = 0;
//                        for (int i = 0; i < 32; i++)
//                        {
//                            if (adc_buf[send_buf[2]][i] <= 800)
//                            {
//                                cnt++;
//                            }
//                        }
//                        if(cnt >= 10)
//                            ncd++;
//                        else
//                            ncd = 0;
//                        if ((ncd >=1) && (ncd <= 10))
//                            ret = 0;
//                        else
//                            ret  = CalcFrame_L32(&dev1);
//                    }
//                    else
//                    if(adc_buf[send_buf[2]][10] < 500)
//                            CLR(0x15);
//                    else
//                            SET(0x15);
                    ret  = CalcFrame_L32(&dev1);
                    if(ret)
                    {
                      
//                        out1_cnt++;
//                        if(out1_cnt >= 3)
//                        {
                          output = 1;
                          out0_cnt = 0;
                          detected_output();    //判断到遮挡
//                        }
                    }                
                    else if(ret == 0)
                    {
                        out0_cnt++;
                        out1_cnt = 0;
                        if((out0_cnt >= 25))
                        {
                            output = 0;
                            out0_cnt = 0;
                            cancel_output();      //无遮挡
                        }
                    }
                }
                else
                {
                    int ret = 0;
                    int cnt = 0;
                    for (int i = 0; i < 32; i++)
                    {
                        if (adc_buf[send_buf[2]][i] <= 325)
                        {
                            cnt++;
                        }
                    }
                    if((send_buf[2] == 4) || (send_buf[2] == 3))
                        cnt-=2;
                    else if((send_buf[2] == 2) || (send_buf[2] == 1))
                        cnt-=1;
                    if(cnt >= 10)
                        ncd++;
                    else
                        ncd = 0;
                    if ((ncd >=1) && (ncd <= 20))
                        ret = 0;
                    else
                        ret  = CalcFrame_L32(&dev1);
                    if(ret)
                    {
                       out1_cnt++;
                       out0_cnt = 0;
                        if(out1_cnt >= 3)
                        {
                            output = 1;
                            out1_cnt = 0;
                            detected_output();    //判断到遮挡
                            ncd = 0;
                        }
                    }                
                    else if(ret == 0)
                    {
                        out0_cnt++;
                        out1_cnt = 0;
                        if((out0_cnt >= 25))
                        {
                            output = 0;
                            out0_cnt = 0;
                            cancel_output();      //无遮挡
                        }
                        if(ncd > 20)
                          ncd = 0;
                    }
                }
               
                
            }
            int ret2 = GetPower_L32(&dev1);
            if((ret2 == 1) && (pwr_state == 0))
            {
                pwr_flag = 1;
                pwr_state = 1;
                pwr_down = 0;
                delay_flag = 1;
            }
            else if((ret2 == -1) && (pwr_state == 1))
            {
                pwr_down++;
                pwr_down = 0;
                pwr_flag = 2;
                pwr_state = 0;
                delay_flag = 1;
            }
            
#endif
            Bt_Run(TIM0);
        }
     }
  
}


/*******************************************************************************
 * BT1中断服务函数
 ******************************************************************************/
void Tim1_IRQHandler(void)              //100us中断
{
    if (TRUE == Bt_GetIntFlag(TIM1))
    {
        Bt_ClearIntFlag(TIM1);
        if(start_flag == 0)
        {
            tick_cnt++;
            if(tick_cnt >= 50000)
            {
                tick_cnt = 0;
                adc_buf2[10] = 0;
                start_flag = 1;
            }
        }
        else
        {
             tick_cnt++;
            if(tick_cnt >= 30000)
            {
                tick_cnt = 0;
                adc_buf2[10] = 1700;
                start_flag = 0;
            }
        }
        if((out_flag == 1) && (buzz_flag == 0))    //遮挡持续50s后启动蜂鸣器
        {
          buzzle_count++;
          if(buzzle_count >= 50000)       //5s
          {
              buzzle_count_s++;
              buzzle_count = 0;
              if(buzzle_count_s >= 10)
              {
                  buzzle_count_s = 0;
                  buzz_flag = 1;
                  //test_flag = 1;
              }
          }
        }
        if(buzz_flag == 1)              //蜂鸣器1s间隔翻转
        {
            buzzle_cnt++;
            if(buzzle_cnt >= 10000)
            {
                buzzle_cnt = 0;
                (buzzle_state%2)?(SET(BUZZER)):(CLR(BUZZER));
                buzzle_state = !buzzle_state;
            }
        }
    }
}

void Tim2_IRQHandler(void)              //100us中断
{
    if (TRUE == Bt_GetIntFlag(TIM2))
    {
        Bt_ClearIntFlag(TIM2);

    }
}

void Tim0_IRQHandler(void)              //20us中断
{
    if (TRUE == Bt_GetIntFlag(TIM0))
    {
        Bt_ClearIntFlag(TIM0);
//        if(test_cnt >= 1200)
//        {
//            test_cnt = 0;
//            send_flag = 1;
//            Bt_Stop(TIM0);
//        }
#if 1
        tick_cnt++;
        if(clk_state)
        {            
            if(pwr_flag  == 1)          //功率提升
            {
                clk_pwr_t++;
                if(clk_pwr_t >= 10)     //200us
                {
                    clk_pwr_t = 0;
                    clk_state = 0;
                    Gpio_WriteOutputIO(GpioPort0, GpioPin3, clk_state);
                    pwr_flag = 0;
                }
            }
            else if(pwr_flag  == 2)     //功率降低
            {
                clk_pwr_t++;
                if(clk_pwr_t >= 8)     //160us
                {
                    clk_pwr_t = 0;
                    clk_state = 0;
                    Gpio_WriteOutputIO(GpioPort0, GpioPin3, clk_state);
                    pwr_flag = 0;
                }
            }
            else
            {
                if(clk_high_cnt > 32)
                {
                    clk_high_t++;
                    if(clk_high_t >= 2+PD_mode)
                    {
                        clk_high_t = 0;
                        clk_high_cnt = 0;
                        clk_state = 0;
                        Gpio_WriteOutputIO(GpioPort0, GpioPin3, clk_state);
                        send_flag = 1;
                        Bt_Stop(TIM0);
                    }
                }
                else{
                    clk_state = 0;
                    Gpio_WriteOutputIO(GpioPort0, GpioPin3, clk_state);
                }
            }
        }
        else{
            if(pwr_flag != 0)
            {
                clk_state = 1;
                Gpio_WriteOutputIO(GpioPort0, GpioPin3 , clk_state);  
            }
            else
            {
                clk_low_t++;
                if(clk_low_t >= 22)         //低电平500us
                {
                    clk_low_t = 0;
                    clk_high_cnt++;                
                    clk_state = 1;                   
                    adc_flag = 1;
                    adc_vt_flag = 1;
                    Gpio_WriteOutputIO(GpioPort0, GpioPin3 , clk_state);
                    if(clk_high_cnt == 33)
                    {
                        PD_mode++;
                        if(PD_mode > 4)
                          PD_mode = 0;
                    }
                }
                else if((clk_low_t >= 19) && (adc_flag == 1))           //440us ADC2
                {
                    if(clk_high_cnt == 0)
                    {
                        if(PD_mode == 2)
                        {
                            led_Cmd(1);
                        }
                        else if(PD_mode == 4)
                        {
                            led_Cmd(2);
                        }
                        else
                        {
                            led_Cmd(0);
                        }
                    }
                    else{
                        Adc_Start();
                    }
                }
                else if ((clk_low_t >= 2) && (adc_vt_flag == 1))        //100us ADC1
                {               
                    if(clk_high_cnt > 0)
                    {
                        Adc_Start();                    
                    }
                }
            }
        }
#endif
#ifndef UART_DEBUG
//        if(start_flag == 1)
//        {
//            tick_cnt++;
//            if(tick_cnt >= 500000)
//            {
//                tick_cnt = 0;
//                 (buzzle_state%2)?(SET(0x32)):(CLR(0x32));
//                buzzle_state = !buzzle_state;
//            }
//        }
//        if((out_flag == 1) && (buzz_flag == 0))    //遮挡持续50s后启动蜂鸣器
//        {
//          buzzle_count++;
//          if(buzzle_count >= 50000)       //1s
//          {
//              buzzle_count_s++;
//              buzzle_count = 0;
//              if(buzzle_count_s >= 50)
//              {
//                  buzzle_count_s = 0;
//                  buzz_flag = 1;
//              }
//          }
//        }
//        if(buzz_flag == 1)              //蜂鸣器1s间隔翻转
//        {
//            buzzle_cnt++;
//            if(buzzle_cnt >= 50000)
//            {
//                buzzle_cnt = 0;
//                (buzzle_state%2)?(SET(BUZZER)):(CLR(BUZZER));
//                buzzle_state = !buzzle_state;
//            }
//        }
#endif
    }
}

void Adc_IRQHandler(void)
{
    if (TRUE == M0P_ADC->IFR_f.CONT_INTF)
    {
        Adc_ClrContIrqState();
        
        
        //Gpio_WriteOutputIO(GpioPort0, GpioPin1 , 0);
        if(adc_vt_flag == 1)
        {
            adc_vt_flag = 0;
            adc_vt_buf[PD_mode][clk_high_cnt-1]=(uint16_t)(M0P_ADC->RESULT_ACC_f.RESULT_ACC/18); //取ADC累加值
            M0P_ADC->CR1_f.RACC_CLR = 0u;//累加寄存器清零
            adc_vt_buf[PD_mode][clk_high_cnt-1] = adc_vt_buf[PD_mode][clk_high_cnt-1] * 0.95;
        }
        else if(adc_flag == 1)
        {
            adc_flag = 0;
            adc_buf[PD_mode][clk_high_cnt-1]=(uint16_t)(M0P_ADC->RESULT_ACC_f.RESULT_ACC/18); //取ADC累加值
//            if(adc_buf[PD_mode][clk_high_cnt-1] >= adc_vt_buf[PD_mode][clk_high_cnt-1])
//                adc_buf[PD_mode][clk_high_cnt-1] = adc_buf[PD_mode][clk_high_cnt-1] - adc_vt_buf[PD_mode][clk_high_cnt-1];
//            else
//                adc_buf[PD_mode][clk_high_cnt-1] = adc_vt_buf[PD_mode][clk_high_cnt-1] - adc_buf[PD_mode][clk_high_cnt-1];
            if((clk_high_cnt == 6) && ((PD_mode == 0) || (PD_mode == 1) || (PD_mode == 3)))
            {
                if(adc_buf[PD_mode][clk_high_cnt-1] >= adc_vt_buf[PD_mode][clk_high_cnt-2])
                    adc_buf[PD_mode][clk_high_cnt-1] = adc_buf[PD_mode][clk_high_cnt-1] - adc_vt_buf[PD_mode][clk_high_cnt-2];
                else
                    adc_buf[PD_mode][clk_high_cnt-1] = adc_vt_buf[PD_mode][clk_high_cnt-2] - adc_buf[PD_mode][clk_high_cnt-1];
            }
            else if((PD_mode == 4) && (clk_high_cnt == 4))
            {
                if(adc_buf[PD_mode][clk_high_cnt-1] >= adc_vt_buf[PD_mode][clk_high_cnt-2])
                    adc_buf[PD_mode][clk_high_cnt-1] = adc_buf[PD_mode][clk_high_cnt-1] - adc_vt_buf[PD_mode][clk_high_cnt-2];
                else
                    adc_buf[PD_mode][clk_high_cnt-1] = adc_vt_buf[PD_mode][clk_high_cnt-2] - adc_buf[PD_mode][clk_high_cnt-1];
            }
            else if((PD_mode == 2) && (clk_high_cnt == 5))
            {
                if(adc_buf[PD_mode][clk_high_cnt-1] >= adc_vt_buf[PD_mode][clk_high_cnt-2])
                    adc_buf[PD_mode][clk_high_cnt-1] = adc_buf[PD_mode][clk_high_cnt-1] - adc_vt_buf[PD_mode][clk_high_cnt-2];
                else
                    adc_buf[PD_mode][clk_high_cnt-1] = adc_vt_buf[PD_mode][clk_high_cnt-2] - adc_buf[PD_mode][clk_high_cnt-1];
            }
            else{
                if(adc_buf[PD_mode][clk_high_cnt-1] >= adc_vt_buf[PD_mode][clk_high_cnt-1])
                    adc_buf[PD_mode][clk_high_cnt-1] = adc_buf[PD_mode][clk_high_cnt-1] - adc_vt_buf[PD_mode][clk_high_cnt-1];
                else
                    adc_buf[PD_mode][clk_high_cnt-1] = adc_vt_buf[PD_mode][clk_high_cnt-1] - adc_buf[PD_mode][clk_high_cnt-1];
            }
            
            M0P_ADC->CR1_f.RACC_CLR = 0u;//累加寄存器清零
            if((PD_mode == 0) || (PD_mode == 1) || (PD_mode == 3))
            {
                if((clk_high_cnt > 0) && (clk_high_cnt < 32))
                {
                    led_Cmd(clk_high_cnt);
                }
            }
            else if(PD_mode == 2)
            {
                if((clk_high_cnt > 0) && (clk_high_cnt < 31))
                {
                    led_Cmd(clk_high_cnt+1);
                }
            }
            else if(PD_mode == 4)
            {
                if((clk_high_cnt > 0) && (clk_high_cnt < 30))
                {
                    led_Cmd(clk_high_cnt+2);
                }
            }
        }
    }
}
/*******************************************************************************
 * BT定时功能测试 （重载模式）
 ******************************************************************************/
void BT_TIM0_int(void)
{
    stc_bt_cfg_t   stcCfg;
    uint16_t          u16ArrData = 65536 - 32;
    uint16_t          u16InitCntData = 65536 - 32;

    //打开BT外设时钟
    Sysctrl_SetPeripheralGate(SysctrlPeripheralBt, TRUE);

    stcCfg.enGateP = BtPositive;
    stcCfg.enGate  = BtGateEnable;
    stcCfg.enPRS   = BtPCLKDiv16;
    stcCfg.enTog   = BtTogDisable;
    stcCfg.enCT    = BtTimer;
    stcCfg.enMD    = BtMode2;
    //Bt初始化
    Bt_Init(TIM0, &stcCfg);

    //TIM1中断使能
    Bt_ClearIntFlag(TIM0);
    Bt_EnableIrq(TIM0);
    EnableNvic(TIM0_IRQn, IrqLevel0, TRUE);

    //设置重载值和计数值，启动计数
    Bt_ARRSet(TIM0, u16ArrData);
    Bt_Cnt16Set(TIM0, u16InitCntData);
    Bt_Run(TIM0);
    M0P_TIM0->CR = 0X0443;
}

void BT_TIM1_int(void)  //100us
{
    stc_bt_cfg_t   stcCfg;
    uint16_t          u16ArrData = 0xff6a;
    uint16_t          u16InitCntData = 0xff6a;

    //打开BT外设时钟
    Sysctrl_SetPeripheralGate(SysctrlPeripheralBt, TRUE);

    stcCfg.enGateP = BtPositive;
    stcCfg.enGate  = BtGateEnable;
    stcCfg.enPRS   = BtPCLKDiv16;
    stcCfg.enTog   = BtTogDisable;
    stcCfg.enCT    = BtTimer;
    stcCfg.enMD    = BtMode2;
    //Bt初始化
    Bt_Init(TIM1, &stcCfg);

    //TIM1中断使能
    Bt_ClearIntFlag(TIM1);
    Bt_EnableIrq(TIM1);
    EnableNvic(TIM1_IRQn, IrqLevel3, TRUE);

    //设置重载值和计数值，启动计数
    Bt_ARRSet(TIM1, u16ArrData);
    Bt_Cnt16Set(TIM1, u16InitCntData);
    Bt_Run(TIM1);
    M0P_TIM1->CR = 0X0443;
}

void BT_TIM2_int(void)  //100us
{
    stc_bt_cfg_t   stcCfg;
    uint16_t          u16ArrData = 0xff6a;
    uint16_t          u16InitCntData = 0xff6a;

    //打开BT外设时钟
    Sysctrl_SetPeripheralGate(SysctrlPeripheralBt, TRUE);

    stcCfg.enGateP = BtPositive;
    stcCfg.enGate  = BtGateEnable;
    stcCfg.enPRS   = BtPCLKDiv16;
    stcCfg.enTog   = BtTogDisable;
    stcCfg.enCT    = BtTimer;
    stcCfg.enMD    = BtMode2;
    //Bt初始化
    Bt_Init(TIM2, &stcCfg);

    //TIM1中断使能
    Bt_ClearIntFlag(TIM2);
    Bt_EnableIrq(TIM2);
    EnableNvic(TIM2_IRQn, IrqLevel3, TRUE);

    //设置重载值和计数值，启动计数
    Bt_ARRSet(TIM2, u16ArrData);
    Bt_Cnt16Set(TIM2, u16InitCntData);
    Bt_Run(TIM2);
    M0P_TIM2->CR = 0X0443;
}

void App_GpioInit(void)
{
    //P33 34 35 36
    //p23 24 25
    stc_gpio_cfg_t stcGpioCfg;
    Sysctrl_SetPeripheralGate(SysctrlPeripheralGpio, TRUE); 
    stcGpioCfg.enDir = GpioDirOut;
    stcGpioCfg.enPu = GpioPuDisable;
    stcGpioCfg.enPd = GpioPdEnable;
    stcGpioCfg.enOD = GpioOdDisable;
    Gpio_WriteOutputIO(GpioPort0, GpioPin3, FALSE);
    Gpio_Init(GpioPort0, GpioPin3, &stcGpioCfg);
    
    Gpio_Init(GpioPort3, GpioPin3, &stcGpioCfg);
    Gpio_Init(GpioPort3, GpioPin4, &stcGpioCfg);
    Gpio_Init(GpioPort3, GpioPin5, &stcGpioCfg);
    Gpio_Init(GpioPort3, GpioPin6, &stcGpioCfg);
    
    Gpio_Init(GpioPort2, GpioPin3, &stcGpioCfg);
    Gpio_Init(GpioPort2, GpioPin4, &stcGpioCfg);
    Gpio_Init(GpioPort2, GpioPin5, &stcGpioCfg);
 #ifdef UART_DEBUG   
    Gpio_Init(GpioPort0, GpioPin2, &stcGpioCfg);
    Gpio_Init(GpioPort0, GpioPin1, &stcGpioCfg);
#endif
    Gpio_Init(GpioPort1, GpioPin4, &stcGpioCfg);        //out2
    Gpio_Init(GpioPort3, GpioPin2, &stcGpioCfg);        //out1
    Gpio_Init(GpioPort1, GpioPin5, &stcGpioCfg);        //buzzer
}

void ADC_init(void)
{
    stc_adc_cfg_t             stcAdcCfg;
    stc_adc_cont_cfg_t        stcAdcContCfg;
    stc_adc_irq_t             stcAdcIrq;    
    
    DDL_ZERO_STRUCT(stcAdcCfg);
    DDL_ZERO_STRUCT(stcAdcContCfg);
    DDL_ZERO_STRUCT(stcAdcIrq);
     
    Sysctrl_SetPeripheralGate(SysctrlPeripheralAdcBgr, TRUE);  //ADCBGR 外设时钟使能
    
    //ADC配置
    Adc_Enable();
    Bgr_BgrEnable();
    
    stcAdcCfg.enAdcOpMode = AdcContMode;                //连续采样模式
    stcAdcCfg.enAdcClkSel = AdcClkSysTDiv1;             //PCLK
    stcAdcCfg.enAdcSampTimeSel = AdcSampTime8Clk;       //8个采样时钟
    stcAdcCfg.enAdcRefVolSel = RefVolSelAVDD;           //参考电压:AVDD
    stcAdcCfg.bAdcInBufEn = FALSE;                      //电压跟随器如果使能，SPS采样速率 <=200K
    stcAdcCfg.enAdcTrig0Sel = AdcTrigDisable;           //ADC转换自动触发设置
    stcAdcCfg.enAdcTrig1Sel = AdcTrigDisable;
    Adc_Init(&stcAdcCfg);    
    
    stcAdcIrq.bAdcIrq = TRUE;                            //转换完成中断函数入口配置使能
    stcAdcIrq.bAdcRegCmp = FALSE;
    stcAdcIrq.bAdcHhtCmp = FALSE;
    stcAdcIrq.bAdcLltCmp = FALSE;
    Adc_CmpCfg(&stcAdcIrq);                              //结果比较中断使能/禁止配置

    stcAdcContCfg.enAdcContModeCh = AdcExInputCH1;      //通道0 P24
    stcAdcContCfg.u8AdcSampCnt    = 0x11u;              //P24 连续累加次数(次数 = 17+1)
    stcAdcContCfg.bAdcResultAccEn = TRUE;               //累加使能
    Adc_ConfigContMode(&stcAdcCfg, &stcAdcContCfg);

    Adc_EnableIrq();                                     //中断使能
    EnableNvic(ADC_IRQn, IrqLevel3, TRUE);
   
}

void _UartBaudCfg(void)
{
    uint16_t timer=0;

    stc_uart_baud_cfg_t stcBaud;
    stc_bt_cfg_t stcBtCfg;
    
    stc_gpio_cfg_t stcGpioCfg;
    DDL_ZERO_STRUCT(stcGpioCfg);
    Sysctrl_SetPeripheralGate(SysctrlPeripheralGpio,TRUE); //使能GPIO模块时钟
    ///<TX
    stcGpioCfg.enDir = GpioDirOut;
    Gpio_Init(GpioPort0, GpioPin1, &stcGpioCfg);
    Gpio_SetAfMode(GpioPort0, GpioPin1, GpioAf3);          //配置P35 端口为URART1_TX
    ///<RX
    stcGpioCfg.enDir = GpioDirIn;
    Gpio_Init(GpioPort0, GpioPin2, &stcGpioCfg);
    Gpio_SetAfMode(GpioPort0, GpioPin2, GpioAf3);          //配置P36 端口为URART1_RX

    DDL_ZERO_STRUCT(stcBaud);
    DDL_ZERO_STRUCT(stcBtCfg);

    //外设时钟使能
    Sysctrl_SetPeripheralGate(SysctrlPeripheralBt,TRUE);//模式0/2可以不使能
    Sysctrl_SetPeripheralGate(SysctrlPeripheralUart1,TRUE);

    stcBaud.bDbaud  = 1u;//双倍波特率功能
    stcBaud.u32Baud = 250000u;//更新波特率位置
    stcBaud.enMode  = UartMode1; //计算波特率需要模式参数
    stcBaud.u32Pclk = Sysctrl_GetPClkFreq(); //获取PCLK
    timer = Uart_SetBaudRate(M0P_UART1, &stcBaud);

    stcBtCfg.enMD = BtMode2;
    stcBtCfg.enCT = BtTimer;
    Bt_Init(TIM1, &stcBtCfg);//调用basetimer1设置函数产生波特率
    Bt_ARRSet(TIM1,timer);
    Bt_Cnt16Set(TIM1,timer);
    Bt_Run(TIM1);

}

void App_UartInit(void)
{
    stc_uart_cfg_t  stcCfg;

    _UartBaudCfg();

    stcCfg.enRunMode = UartMode1;//测试项，更改此处来转换4种模式测试
    Uart_Init(M0P_UART1, &stcCfg);

    ///< UART中断配置
    Uart_EnableIrq(M0P_UART1, UartRxIrq);
    Uart_ClrStatus(M0P_UART1, UartRC);
    EnableNvic(UART1_IRQn, IrqLevel3, TRUE);

}

void App_ClkInit(void)
{
    stc_sysctrl_clk_cfg_t stcCfg;

    ///< 开启FLASH外设时钟
    Sysctrl_SetPeripheralGate(SysctrlPeripheralFlash, TRUE);

    ///<========================== 时钟初始化配置 ===================================
    ///< 因要使用的时钟源HCLK小于24M：此处设置FLASH 读等待周期为0 cycle(默认值也为0 cycle)
    //Flash_WaitCycle(FlashWaitCycle0);

    ///< 时钟初始化前，优先设置要使用的时钟源：此处设置RCH为4MHz
    Sysctrl_SetRCHTrim(SysctrlRchFreq4MHz);

    ///< 选择内部RCH作为HCLK时钟源;
    stcCfg.enClkSrc    = SysctrlClkRCH;
    ///< HCLK SYSCLK/1
    stcCfg.enHClkDiv   = SysctrlHclkDiv1;
    ///< PCLK 为HCLK/1
    stcCfg.enPClkDiv   = SysctrlPclkDiv1;
    ///< 系统时钟初始化
    Sysctrl_ClkInit(&stcCfg);
}

void App_Rch4MHzTo24MHz(void)
{
///<============== 将时钟从RCH4MHz切换至RCH24MHz ==============================
    ///< RCH时钟不同频率的切换，需要先将时钟切换到RCL，设置好频率后再切回RCH
    Sysctrl_SetRCLTrim(SysctrlRclFreq32768);
    Sysctrl_ClkSourceEnable(SysctrlClkRCL, TRUE);
    Sysctrl_SysClkSwitch(SysctrlClkRCL);

    ///< 加载目标频率的RCH的TRIM值
    Sysctrl_SetRCHTrim(SysctrlRchFreq24MHz);
    ///< 使能RCH（默认打开，此处可不需要再次打开）
    //Sysctrl_ClkSourceEnable(SysctrlClkRCH, TRUE);
    ///< 时钟切换到RCH
    Sysctrl_SysClkSwitch(SysctrlClkRCH);
    ///< 关闭RCL时钟
    Sysctrl_ClkSourceEnable(SysctrlClkRCL, FALSE);

    ///< 使能HCLK从PA01输出
    Gpio_SfHClkOutputCfg(GpioSfHclkOutEnable, GpioSfHclkOutDiv1);

    //delay1ms(3000);

    ///< 禁止HCLK从PA01输出
    Gpio_SfHClkOutputCfg(GpioSfHclkOutDisable, GpioSfHclkOutDiv1);

}

void uart1_sendStr(uint8_t *data, uint32_t len)
{
  while(len --)  
  {
    //Uart_SetTb8(UARTCH1,Even,*data);
    Uart_SendDataPoll(M0P_UART1, *data);
    data ++;
  }
}

void Uart1_IRQHandler(void)
{
    if(TRUE == Uart_GetStatus(M0P_UART1, UartRC))
    {
        Uart_ClrStatus(M0P_UART1, UartRC);
    }

}
void App_WdtInit1(void)
{
    ///< 开启WDT外设时钟
    Sysctrl_SetPeripheralGate(SysctrlPeripheralWdt,TRUE);
    ///< WDT 初始化
    Wdt_Init(WdtResetEn, WdtT1s64);
}
void App_WdtInit(void)
{
    ///< 开启WDT外设时钟
    Sysctrl_SetPeripheralGate(SysctrlPeripheralWdt,TRUE);
    ///< WDT 初始化
    Wdt_Init(WdtResetEn, WdtT820ms);
}